<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
<!--          <el-form-item label="场地ID" prop="positionId">-->
<!--            <el-input v-model="queryParams.positionId" placeholder="请输入场地ID" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="场地格子规格" prop="positionSpecId">-->
<!--            <el-input v-model="queryParams.positionSpecId" placeholder="请输入场地格子规格" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
          <el-form-item label="设备编号" prop="deviceNo">
            <el-input v-model="queryParams.deviceNo" placeholder="请输入设备编号" clearable style="width: 240px" @keyup.enter="handleQuery" disabled/>
          </el-form-item>
          <el-form-item label="串口编号" prop="serialNo">
            <el-input v-model="queryParams.serialNo" placeholder="请输入串口编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="串口索引" prop="serialIndex">
            <el-input v-model="queryParams.serialIndex" placeholder="请输入串口索引" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="蓝牙编号" prop="macNo">
            <el-input v-model="queryParams.macNo" placeholder="请输入蓝牙编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="格子类型" prop="gridType">
            <el-select v-model="queryParams.gridType" placeholder="请选择格子规格" clearable>
              <el-option
                v-for="dict in grid_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="格子规格" prop="specCode">
            <el-select v-model="queryParams.specCode" placeholder="请选择格子规格" clearable>
              <el-option
                v-for="dict in grid_spec"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="格子状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择格子状态" clearable>
              <el-option
                v-for="dict in grid_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:deviceGrid:add']">新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:deviceGrid:edit']">修改</el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['device:deviceGrid:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Open" :disabled="multiple" @click="handleOpen()" v-hasPermi="['device:deviceGrid:remove']">开锁</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:deviceGrid:export']">导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="deviceGridList" @selection-change="handleSelectionChange" border="true">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" width="55" align="center" label="#" fixed="left"/>
        <el-table-column label="格子ID" align="center" prop="deviceGridId" v-if="false" />
        <el-table-column label="名称" align="center" prop="name" fixed="left"/>
        <el-table-column label="编号" align="center" prop="number" />
        <el-table-column label="格子规格" align="center" prop="specCode">
          <template #default="scope">
            <dict-tag :options="grid_spec" :value="scope.row.specCode"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="设备ID" align="center" prop="deviceId" />-->
        <el-table-column label="设备编号" align="center" prop="deviceNo" width="180"/>
        <el-table-column label="串口编号" align="center" prop="serialNo" />
        <el-table-column label="串口索引" align="center" prop="serialIndex" />
        <el-table-column label="蓝牙编号" align="center" prop="macNo" />
        <el-table-column label="格子类型" align="center" prop="gridType">
          <template #default="scope">
            <dict-tag :options="grid_type" :value="scope.row.gridType"/>
          </template>
        </el-table-column>
        <el-table-column label="格子状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="grid_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="设备名称" align="center" prop="deviceName" width="120" show-overflow-tooltip="true"/>
        <el-table-column label="设备地址" align="center" prop="deviceLocation" />
        <el-table-column label="设备类型" align="center" prop="deviceType" width="100">
          <template #default="scope">
            <dict-tag :options="device_type" :value="scope.row.deviceType"/>
          </template>
        </el-table-column>
        <el-table-column label="场地名称" align="center" prop="positionName" width="120" show-overflow-tooltip="true"/>
        <el-table-column label="场地地址" align="center" prop="positionLocation" width="180" show-overflow-tooltip="true"/>
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="220">
          <template #default="scope">
            <el-tooltip content="开锁" placement="top">
              <el-button link type="primary" icon="Open" @click="handleOpen(scope.row)">开锁</el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:deviceGrid:edit']">编辑</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:deviceGrid:remove']">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改设备格子信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="deviceGridFormRef" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="场地ID" prop="positionId">-->
<!--          <el-input v-model="form.positionId" placeholder="请输入场地ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="设备场地" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择" @change="handlePositionChange" disabled>
            <el-option
              v-for="item in positionList"
              :key="item.positionId"
              :label="item.name"
              :value="item.positionId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属设备" prop="deviceId">
          <el-select v-model="form.deviceId" placeholder="请选择设备" @change="handleDeviceChange" disabled>
            <el-option
              v-for="item in deviceListByPosition"
              :key="item.deviceId"
              :label="item.name"
              :value="item.deviceId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceNo">
          <el-input v-model="form.deviceNo" placeholder="请输入编号" maxlength="20" show-word-limit disabled/>
        </el-form-item>
        <el-form-item label="格子规格" prop="specCode">
          <el-select v-model="form.specCode" placeholder="请选择格子规格">
            <el-option
              v-for="dict in grid_spec"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="格子类型" prop="gridType">
          <el-select v-model="form.gridType" placeholder="请选择格子类型">
            <el-option
              v-for="dict in grid_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="格子名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" maxlength="10" show-word-limit/>
        </el-form-item>
        <el-form-item label="格子编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入编号" maxlength="10" show-word-limit/>
        </el-form-item>
        <el-form-item label="串口编号" prop="serialNo" v-if="serialEnabled">
          <el-input v-model="form.serialNo" placeholder="请输入串口编号" maxlength="30" show-word-limit/>
        </el-form-item>
        <el-form-item label="串口索引" prop="serialIndex" v-if="serialEnabled">
          <el-input v-model="form.serialIndex" placeholder="请输入串口索引" maxlength="30" show-word-limit/>
        </el-form-item>
        <el-form-item label="蓝牙编号" prop="macNo" v-if="bluetoothEnabled">
          <el-input v-model="form.macNo" placeholder="请输入蓝牙编号" maxlength="30" show-word-limit/>
        </el-form-item>
        <el-form-item label="格子状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择格子状态">
            <el-option
                v-for="dict in grid_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" maxlength="50" show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DeviceGrid" lang="ts">
import {
  listDeviceGrid,
  getDeviceGrid,
  delDeviceGrid,
  addDeviceGrid,
  updateDeviceGrid,
  openDeviceGrid
} from '@/api/device/deviceGrid';
import { DeviceGridVO, DeviceGridQuery, DeviceGridForm } from '@/api/device/deviceGrid/types';
import {allPosition} from "@/api/device/position";
import {listDevice} from "@/api/device/device";

const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { grid_status,grid_spec,grid_type,device_type } = toRefs<any>(proxy?.useDict('grid_status','grid_spec','grid_type','device_type'));

const deviceGridList = ref<DeviceGridVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const bluetoothEnabled = ref(false);
const serialEnabled = ref(false);

const queryFormRef = ref<ElFormInstance>();
const deviceGridFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceGridForm = {
  deviceGridId: undefined,
  positionId: undefined,
  specCode: undefined,
  deviceId: undefined,
  deviceNo: undefined,
  name: undefined,
  number: undefined,
  serialNo: undefined,
  serialIndex: undefined,
  macNo: undefined,
  gridType: undefined,
  status: undefined,
  remark: undefined
}
const data = reactive<PageData<DeviceGridForm, DeviceGridQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    positionId: undefined,
    specCode: undefined,
    deviceId: undefined,
    deviceNo: undefined,
    name: undefined,
    number: undefined,
    serialNo: undefined,
    serialIndex: undefined,
    macNo: undefined,
    gridType: undefined,
    status: undefined,
    params: {
    }
  },
  positionList:[],
  deviceList:[],
  deviceListByPosition:[],
  rules: {
    deviceGridId: [
      { required: true, message: "格子ID不能为空", trigger: "blur" }
    ],
    positionId: [
      { required: true, message: "场地ID不能为空", trigger: "blur" }
    ],
    specCode: [
      { required: true, message: "场地格子规格不能为空", trigger: "blur" }
    ],
    deviceId: [
      { required: true, message: "设备ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    number: [
      { required: true, message: "编号不能为空", trigger: "blur" }
    ],
    serialNo: [
      { required: true, message: "串口编号不能为空", trigger: "blur" }
    ],
    serialIndex: [
      { required: true, message: "串口索引不能为空", trigger: "blur" }
    ],
    macNo: [
      { required: true, message: "蓝牙编号不能为空", trigger: "blur" }
    ],
    gridType: [
      { required: true, message: "类型：common 常规,screen 屏幕使用,special 特殊用途不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "格子状态：locker 已占用,unlock 未使用不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules,positionList,deviceList,deviceListByPosition } = toRefs(data);

/**
 * 选择场地联动设备
 * @param val
 */
function handlePositionChange(val: number) {
  form.value.deviceId = undefined;
  deviceListByPosition.value = deviceList.value.filter(item => item.positionId === val);
}

/**
 * 选择设备事件
 * @param val
 */
function handleDeviceChange(val: number) {
  const device = deviceList.value.find(item => item.deviceId === val);
  form.value.deviceNo = device.deviceNo;
  if (device.deviceType === 'bluetooth'){
    bluetoothEnabled.value = true;
  }
  if (device.deviceType === 'serial'){
    serialEnabled.value = true;
  }
}

/** 查询设备格子信息列表 */
const getList = async (param) => {
  if (param){
    const deviceNo = route.params && route.params.deviceNo;
    if (deviceNo) {
      queryParams.value.deviceNo = deviceNo;
    }else {
      queryParams.value.deviceNo = '121313213132';
    }
  }
  loading.value = true;
  const res = await listDeviceGrid(queryParams.value);
  deviceGridList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
}

/**
 * 获取场地信息
 */
const getPositionList = async () => {
  loading.value = true;
  const res = await allPosition();
  positionList.value = res.data;
  loading.value = false;
}

/**
 * 获取设备信息
 */
const getDeviceList = async () => {
  loading.value = true;
  const res = await listDevice();
  deviceList.value = res.data.records;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  deviceGridFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceGridVO[]) => {
  ids.value = selection.map(item => item.deviceGridId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  const deviceId = route.params && route.params.deviceId;
  const deviceNo = route.params && route.params.deviceNo;
  const positionId = route.params && route.params.positionId;
  form.value.positionId = positionId;
  form.value.deviceId = undefined;
  deviceListByPosition.value = deviceList.value.filter(item => item.positionId === positionId);
  form.value.deviceId = deviceId;
  form.value.deviceNo = deviceNo;
  serialEnabled.value = false;
  bluetoothEnabled.value = false;
  dialog.visible = true;
  dialog.title = "添加设备格子信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceGridVO) => {
  reset();
  const _deviceGridId = row?.deviceGridId || ids.value[0]
  const res = await getDeviceGrid(_deviceGridId);
  if (row.deviceType === 'bluetooth'){
    bluetoothEnabled.value = true;
  }
  if (row.deviceType === 'serial'){
    serialEnabled.value = true;
  }
  deviceListByPosition.value = deviceList.value.filter(item => item.positionId === res.data.positionId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改设备格子信息";
}

/** 提交按钮 */
const submitForm = () => {
  deviceGridFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.deviceGridId) {
        await updateDeviceGrid(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addDeviceGrid(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceGridVO) => {
  const _deviceGridIds = row?.deviceGridId || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备格子信息编号为"' + _deviceGridIds + '"的数据项？').finally(() => loading.value = false);
  await delDeviceGrid(_deviceGridIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 开锁按钮操作 */
const handleOpen = async (row?: DeviceGridVO) => {
  const _deviceGridIds = row?.deviceGridId || ids.value;
  await proxy?.$modal.confirm('是否确认打开所勾选的柜子？').finally(() => loading.value = false);
  await openDeviceGrid(_deviceGridIds);
  proxy?.$modal.msgSuccess("开锁成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('device/deviceGrid/export', {
    ...queryParams.value
  }, `deviceGrid_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList(true);
  getPositionList();
  getDeviceList();
});
</script>
